package com.xxl.job.core.util;

import cn.hutool.core.thread.ExecutorBuilder;
import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author liutao
 * @date 2022年02月28日 10:45
 */
public class ExecutorHelper {

    private ExecutorHelper(){};

    private static final class ExecutorHelperHolder {
        private static final ExecutorHelper INSTANCE = new ExecutorHelper();
    }

    public static ExecutorHelper getInstance() {
        return ExecutorHelperHolder.INSTANCE;
    }

    public ExecutorService createSingleExecutor(String name) {
        name = name + " | executor-pool-%d";
        return ExecutorBuilder.create()
                .setCorePoolSize(1)
                .setMaxPoolSize(1)
                .setKeepAliveTime(0L)
                .setThreadFactory(new ThreadFactoryBuilder().setNameFormat(name).build())
                .build();
    }

    public void shutdown(ExecutorService executorService) {
        executorService.shutdown();
        try {
            if (!executorService.awaitTermination(800, TimeUnit.MILLISECONDS)) {
                executorService.shutdownNow();
            }
        } catch (InterruptedException e) {
            executorService.shutdownNow();
        }
    }
}
